package ntd.block.server.impl;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import io.netty.handler.codec.ByteToMessageDecoder;
import lj.netty.ToolNettyInit;
import lj.netty.bean.LJNettyBo;
import lj.netty.bean.LJNettyInitContext;
import lj.netty.listen.LJCNettyListen;
import ntd.block.server.ComServer;
import ntd.block.server.bo.ComServerInBo;
import ntd.block.server.bo.ComServerMsgBo;

/**
 * 交互应用 - tcp实现
 */
public class ComServerTcp extends ComServerBase implements ComServer {

    /** nettyTcp 服务 */
    private ToolNettyInit toolNettyInit;

    @Override
    public void init(ComServerInBo comServerInBo) {
        if (ObjectUtil.isNull(comServerInBo)) {
            return;
        }
        ComServerTcp comServerTcp = this;

        toolNettyInit = new ToolNettyInit(new LJNettyInitContext().setPort(comServerInBo.getPort()).setLJCNettyListen(new LJCNettyListen() {
            @Override
            public void onInit(LJNettyBo LJNettyBo) {
            }

            @Override
            public void onMsg(LJNettyBo LJNettyBo) {
                comServerTcp.onMsg(ComServerMsgBo.transform(LJNettyBo));
            }

            @Override
            public void onClose(LJNettyBo LJNettyBo) {
                comServerTcp.onClose(ComServerMsgBo.transform(LJNettyBo));
            }

            @Override
            public ByteToMessageDecoder struct() {
                return null;
            }
        }));

        ThreadUtil.execAsync(() -> {
            toolNettyInit.start();
        });
        StaticLog.info("tcp服务[{}]启动成功！", comServerInBo.getPort());
    }

    @Override
    public void close() {
        toolNettyInit.close();
    }


    public static void main(String[] args) {
        ComServerTcp comServerTcp = new ComServerTcp() {
            @Override
            protected void onMsg(ComServerMsgBo comServerMsgBo) {
                StaticLog.info(JSONUtil.toJsonStr(comServerMsgBo));
            }
        };

        ComServerInBo comServerInBo1 = new ComServerInBo();
        comServerInBo1.setPort(36059);

        comServerTcp.init(comServerInBo1);
    }
}
